//
//  ZYXWebViewController.m
//  Internet
//
//  UIWebView 使用
//

#import "ZYXWebViewController.h"
#import "MBProgressHUD+MJ.h"

@interface ZYXWebViewController () <UIWebViewDelegate, UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
- (IBAction)back:(id)sender;
- (IBAction)forward:(id)sender;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;

@end

@implementation ZYXWebViewController

/**
 UIWebView : 浏览器, 浏览文件 : HTML\HTM, txt, doc, ppt, mp4, pdf
 */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 0.设置导航栏中间的内容
//        UISearchBar *searchBar = [[UISearchBar alloc] init];
//        searchBar.frame = CGRectMake(0, 0, 300, 40);
//        searchBar.delegate = self;
//        self.navigationItem.titleView = searchBar;
    
    // 1.创建请求
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.设置webView的代理
    self.webView.delegate = self;
    // 伸缩内容至适应屏幕尺寸
    //    self.webView.scalesPageToFit = YES;
    
    // 3.加载请求
    [self.webView loadRequest:request];
}


#pragma mark - UISearchBarDelegate
/**
 *  搜索框的文字改变了
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    ZYXLog(@"searchBar:textDidChange: ----%@", searchText);
}

/**
 *  点击了"搜索"按钮
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 开始加载网页
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", searchBar.text]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}


#pragma mark - UIWebViewDelegate
/**
 *  UIWebView开始加载资源的时候调用(开始发送请求)
 */
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    ZYXLog(@"webViewDidStartLoad---UIWebView开始加载资源 发送请求");
    
    [MBProgressHUD showMessage:@"网络资源正在加载中..."];
}

/**
 *  UIWebView加载完毕的时候调用(请求完毕)
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    ZYXLog(@"webViewDidFinishLoad---UIWebView加载完毕 ");
    
    [MBProgressHUD hideHUD];
    
    // 控制器前进和回退按钮的可用性
    self.backItem.enabled       = [webView canGoBack];
    self.forwardItem.enabled    = [webView canGoForward];
    
    // 获得当前网页的标题
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
}

/**
 *  UIWebView加载失败的时候调用(请求失败)
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    ZYXLog(@"didFailLoadWithError---");
    
    [MBProgressHUD hideHUD];
}

- (IBAction)back:(id)sender {
    [self.webView goBack];
}

- (IBAction)forward:(id)sender {
    [self.webView goForward];
}

@end
